const path = require("path")
const fs = require("fs")
const Stock = require("../../modules/Stock")
const $asyncForeach = require("../../utils/asyncForeach")
const $request = require("../../utils/request")

const recommendListPath = path.resolve(__dirname, "../../cache/recommendList.json")

let isScaning = false

module.exports = async () => {

    if (!isScaning) {
        isScaning = true
        fs.writeFileSync(recommendListPath, "[]")

        let individualList = await Stock.getIndividualList()

        setTimeout(async () => {

            try {
                await $asyncForeach({
                    list: individualList, fn: async ({ code }, index) => {

                        let stock = new Stock({ code, type: "stock" })
                        let transaction = await stock.getTransaction({ ktype: "year" })
                        let details = await stock.generateDetails({ transaction })
                        let detailsLatest = Stock.getDetailsLatest({ details })

                        let divergence = Stock.divergence({ details: detailsLatest })
                        let latestKd = Stock.latestKd({ details: detailsLatest })
                        let latestMaDifference = Stock.latestMaDifference({ details: detailsLatest })

                        let list = JSON.parse(fs.readFileSync(recommendListPath, { encoding: "utf-8" }))

                        let [prevTransaction, nowTransaction] = detailsLatest.transaction.slice(-2)

                        if (
                            (prevTransaction && nowTransaction)
                            && (prevTransaction.ma5 > nowTransaction.ma5) // ma5是往下的
                            && (nowTransaction.high < prevTransaction.ma5) // 这条K线的最高点未触及ma5
                            && (latestMaDifference.percentage <= -30) // 要离ma5至少有30%以上
                        ) {
                            detailsLatest.analysis = { divergence, latestKd, latestMaDifference }

                            list.push(detailsLatest)
                            fs.writeFileSync(recommendListPath, JSON.stringify(list))
                        }

                        console.log(`${index + 1}/${individualList.length} ${code} listLength: ${list.length}`)
                    }
                })
            }
            catch (e) {

            }

            await $request({
                url: "https://cong.yuyoupx.com/api/stock/recommend/save",
                method: "POST",
                data: {
                    recommendList: fs.readFileSync(recommendListPath, { encoding: "utf-8" })
                }
            })

            isScaning = false

        })
    }

}